#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import countries

# Get a list of equivalent names for the country.
# Example: given "United States", return [u"United States", u"United States of America", etc]
# Doesn't deal with character case... TODO: deal with character case
def get_country_equiv(name):
		# Check if name is normalized. This will speed up lookups.
		c = countries.country_list
		if c.has_key(name):
				return c[name] 
		# Otherwise, brute force search for it. TODO: speed this up
		for k, v in c.items():
				if name in v:
						return v
		return None
		
# Get the ISO_3166-1_alpha-2 name of the country. This is a way get a normalized
# name for a country for storage. Using this name will speed up lookups.
def get_standard_name(name):
		c = countries.country_list
		for k, v in c.items():
				if name in v:
						return k
		return None
		
if '__main__' == __name__:
		if len(sys.argv) != 3:
				
				print "usage: countryequiv.py (standard|equivs) (country name)"
				sys.exit(1)
		if sys.argv[1] not in ('standard', 'equivs'):
				print "usage: countryequiv.py (standard|equivs) (country name)"
				print "second argument must be either 'standard' or 'equivs'"
				sys.exit(1)
		if sys.argv[1] == 'standard':
				print get_standard_name(sys.argv[2])
				sys.exit(0)
		elif sys.argv[1] == 'equivs':
				equivs = get_country_equiv(sys.argv[2])
				equivs_len = len(equivs)
				i = 1
				for e in equivs:
						if i == equivs_len:
								print "%s " % (e, )
								break
						else:
								print "%s, " % (e, ), 
								i += 1
				sys.exit(0)
		else:
				# No idea how we got here!
				print "Serious error! Please report!!!"
				sys.exit(0)